import {
  scanQrCodesKey,
  qrCodesGenerate,
  detectionQrCodesGenerate,
  getLoginStatus,
  getIdCardInfo,
  getMusicInfo,
  getUserInfo,
  getIdGrade,
  getIdBindingInfo,
  logOut,
  getVipInfo,
  getCaptchaSent,
  getCaptchaVerify,
  getLoginCellphone,
  getUserRecord,
  getUserPlaylist
} from "@/api/login/index"
import {getDailySignin} from "@/api/home/index"

import {setLocalStorage, getLocalStorage, removeLocalStorage} from "@/utils/auth"

import {Notify} from "vant";
import router from "@/router/index";




const loginGather = {
  /**
   *@params：
   *@desc：获取手机验证码登录
   *@author：羽
   *@date 2022/08/06 16:34:05
   *
   */
  getCaptchaSent(phone) {
   return getCaptchaSent({ phone }).then(res => {
      return res.code
    })
  },
  // 验证验证码是否和手机号匹配
  // params: { phone,captcha }
  getCaptchaVerify(params) {
   return  getCaptchaVerify(params).then(res => {
     // console.log(res)
     if(res.code === 200) {
        return this.getLoginCellphone(params)
      }
    }).catch(err => {
      Notify({
        background: 'red',
        color: 'white',
        message: '验证码和手机号不匹配'
      })
    })
  },
  // 登录
  getLoginCellphone(params) {
    return getLoginCellphone(params).then(res => {
      // console.log(res)
      if (Number(res.code) === 200) {
        // 存储token
        setLocalStorage('cookies', res.cookie)
        this.token = res.cookie
        // 还会返回一个token这个token可以使用刷新token的接口进行刷新 res.token，目前不知道作用
        return res
      }
    }).catch(err => {
      // console.log(err)
    })
  },
  /**
   *@params：
   *@desc：手机扫码登录
   *@author：羽
   *@date 2022/08/06 16:33:45
   */
  // 获取二维码unikey
  getKey() {
    scanQrCodesKey().then(res => {
      const {code, data} = res
      if (Number(code) === 200) {
        this.sweepLoginCode.unikey = data.unikey // 获取key值用来扫码登录
        this.getQrCodesGenerate()
      } else {
        console.log('获取key失败')
      }
    })
  },
  // 获取二维码
  getQrCodesGenerate() {
    qrCodesGenerate(this.sweepLoginCode.unikey).then(resolve => {
      const {code, data} = resolve
      if (Number(code) === 200) {
        // 获取base64图片
        this.sweepLoginCode.qrimg = data.qrimg
        this.getLoginFlag()
      }
    })
  },
  // 这个是定时校验是否扫码成功
  getLoginFlag() {
    if (!this.token) {
      if (this.timer) clearInterval(this.timer)
      this.timer = setInterval(() => {
        detectionQrCodesGenerate(this.sweepLoginCode.unikey).catch((err) => {
          this.sweepLoginCode.code = err.code
          if (err.code === 800) {
            // console.log('二维码已过期')
            clearInterval(this.timer)
          } else if (err.code === 801) {
            // console.log('等待扫码登录')
          } else if (err.code === 802) {
            // console.log('等待确认')
            this.sweepLoginCode.loading = true
          } else if (err.code === 803) {
            this.sweepLoginCode.loading = false
            // 清除定时器
            clearInterval(this.timer)
            // 存储token
            setLocalStorage('cookies', err.cookie)
            this.token = err.cookie
          }
        })
      }, 1000)
    }
  },
  // 获取用户登录状态
  getLoginStatus() {
    getLoginStatus(this.token).catch(err => {
      const {code, profile, account} = err.data

      if (Number(code) === 200 && profile) {
        // console.log(err)
        this.userInfo = profile
        // 所有获取用户信息
        this.getUserInfo(this.userInfo.userId)
        // 获取vip信息
        this.getVipInfo()
        // 获取用户账号信息
        this.getIdCardInfo()
        // 获取用户等级信息
        this.getIdGrade()
        // 获取用户绑定的信息
        this.getIdBindingInfo()
        // 获取粉丝
        this.getUserFollows()
      } else {
        removeLocalStorage('cookies')
      }
    })
  },
  // 获取用户信息
  getUserInfo(id) {
    return getUserInfo(id).then(res => {
      if (Number(res.code) === 200) {
        this.allUserInfo = res
        // console.log(res)
        return res
      }
    })
  },
  // 获取账号信息
  getIdCardInfo() {
    getIdCardInfo(this.token).then(res => {
      // console.log('获取账号信息', res)
    })
  },
  // // 获取用户信息 , 歌单，收藏，mv, dj 数量
  getMusicInfo() {
    return getMusicInfo(this.token).then(res => {
      if (Number(res.code) === 200) return res
    })
  },
  // 获取用户等级信息
  getIdGrade() {
    getIdGrade(this.token).then(res => {
      // console.log('获取用户等级信息', res)
    })
  },
  // 获取用户绑定的信息
  getIdBindingInfo() {
    getIdBindingInfo(this.userInfo.userId).then(res => {
      // console.log('获取用户绑定的信息', res)
    })
  },
  // 获取vip等级信息
  getVipInfo() {
    return getVipInfo().then(res => {
      const { code, data } = res
      if (Number(code) === 200) {
        this.vipInfo = data
        return data
        // console.log(data)
      }
    })
  },
  // 退出登录
  async logOut() {
    await logOut()
    // 清空token
    removeLocalStorage('cookies')
    this.token = ''
    this.userInfo = {}
    return new Promise(resolve => {
      resolve()
    })
  },
  // 签到
  getDailySignin() {
    getDailySignin().then(res => {
      const { code, point } = res
      // point
      if (Number(code) === 200) {
        Notify(`获得${point}经验`)
        this.allUserInfo.pcSign = true
      }
    })
  },
  // 获取用户听歌记录{ uid, type : type=1 时只返回 weekData, type=0 时返回 allData }
  getUserRecord(params) {
    return getUserRecord(params).then(res => {
      if (Number(res.code) === 200) {
        return res
      }
    }).catch(err => {
      return err
    })
  },
  // 获取用户歌单 // { uid, limit offset }
  getUserPlaylist({ uid, num = 0 }) {
    return getUserPlaylist({ uid, limit: 20, offset: num * 20 }).then(res => {
      const { code, playlist } = res
      if (Number(code) === 200) {
        return playlist
      }
    })
  }
}
const userGetters = {
  // 获取少数用户信息
  getUserInfoGetters() {
    return this.userInfo
  },
  // 获取完整用户信息
  getAllUserInfoGetters() {
    return this.allUserInfo
  },
  // 获取Vip信息
  getVipInfoGetters() {
    return this.vipInfo
  }
}
const userGather = {
  token: getLocalStorage('cookies') || '',
  sweepLoginCode: {
    qrimg: '', // 扫码登录获取链接
    unikey: '', // 获取的key值
    loading: false, // 扫码登录状态
    code: '' // 登录状态码
  },
  timer: null, // 定时器
  userInfo: {}, // 少用户信息
  allUserInfo: {}, // 多用户信息
  vipInfo: {}, // 用户vip信息
  verificationCodeInfo: {
    verification: '', // 验证码
  }, // 验证码登录信息
}

export {
  loginGather,
  userGather,
  userGetters
}
